/*
 * Copyright (c) 2023 OceanBase.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.oceanbase.odc.service.flow.task;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.oceanbase.odc.common.trace.TraceContextHolder;
import com.oceanbase.odc.service.objectstorage.cloud.CloudObjectStorageService;
import com.oceanbase.tools.datamocker.core.task.TableTaskContext;
import com.oceanbase.tools.datamocker.core.write.output.MockerFile;
import com.oceanbase.tools.datamocker.schedule.impl.DefaultScheduler;

import lombok.extern.slf4j.Slf4j;

/**
 * custom scheduler for mock task
 *
 * @author yh263208
 * @date 2021-04-27 11:30
 * @since ODC_release_2.4.1
 */
@Slf4j
public class CustomMockScheduler extends DefaultScheduler {

    private final Map<String, String> traceContext;
    private final CloudObjectStorageService cloudObjectStorageService;
    private final OssTaskReferManager taskReferManager;

    public CustomMockScheduler(int maxConnectionSize, Map<String, String> traceContext,
            OssTaskReferManager taskReferManager, CloudObjectStorageService cloudObjectStorageService) {
        super(maxConnectionSize);
        this.traceContext = traceContext;
        this.cloudObjectStorageService = cloudObjectStorageService;
        this.taskReferManager = taskReferManager;
    }

    @Override
    protected void onSuccess(TableTaskContext context) {
        TraceContextHolder.span(traceContext);
        log.info(
                "The data mock for table has been completed, status={},table={},planGeneration={},actualGeneration={},currentRecord={}",
                context.getStatus(), String.format("%s.%s", context.getSchema(), context.getTableName()),
                context.getTotalCount(), context.getTotalDataGenerateCount(), context.getCurrentRecordNum());
        if (cloudObjectStorageService.supported()) {
            /**
             * this is public aliyun mode, the file which generated by data-mocker have to upload to oss server
             * to reduce the usage of local disk
             */
            log.info("ODC will upload mock data file to oss server");
            List<MockerFile> managerList = context.getFileManagers();
            if (managerList != null && managerList.size() != 0) {
                File mockFile = managerList.get(0).getFile();
                if (mockFile != null && mockFile.exists()) {
                    try {
                        String objectName = cloudObjectStorageService.uploadTemp(mockFile.getName(), mockFile);
                        taskReferManager.put(context.getTableTaskId(), objectName);
                        log.info("Upload the data file to the OSS server successfully, tableTaskId={},objectName={}",
                                context.getTableTaskId(), objectName);
                    } catch (IOException exception) {
                        log.warn("Fail to upload file to OSS, fileName={}", mockFile.getName(),
                                exception);
                    } finally {
                        if (mockFile.delete()) {
                            log.info("Temporary data file deleted successfully, filePath={}",
                                    mockFile.getAbsolutePath());
                        } else {
                            log.error("Fail to delete temporary data file, filePath={}",
                                    mockFile.getAbsolutePath());
                        }
                    }
                } else {
                    log.warn("The mock data file does not exist");
                }
            }
        }
        TraceContextHolder.clear();
    }

    @Override
    protected void onFailure(TableTaskContext context, Throwable e) {
        TraceContextHolder.span(traceContext);
        log.warn("The data mock for table has been failed, status={},table={}", context.getStatus(),
                String.format("%s.%s", context.getSchema(), context.getTableName()), e);
        TraceContextHolder.clear();
    }
}
